package com.example.mywiseelves.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.mywiseelves.R;
import com.example.mywiseelves.adapter.IllustrateAdapter;
import com.example.mywiseelves.bean.ElvesBean;
import com.example.mywiseelves.bean.UserBean;
import com.example.mywiseelves.dao.ElvesDao;
import com.example.mywiseelves.dao.UserDao;
import com.example.mywiseelves.utils.PaddingDecoration;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link IllustrateFragment#newInstance} factory method to
 * create an instance of this fragment.
 * 图鉴界面
 */
public class IllustrateFragment extends Fragment implements View.OnClickListener {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    //图鉴列表
    RecyclerView illustrateRecyclerView;
    //用户祈愿点
    TextView userAndPointTextView;
    //页码
    TextView pageTv;
    //精灵数据源
    List<ElvesBean> elvesBeanList = new ArrayList<ElvesBean>();
    //列表适配器
    IllustrateAdapter illustrateAdapter;
    //布局
    View view;
    int page=1;
    int allPage;
    ImageView previousPageIv;
    ImageView nextPageIv;
    //用户dao对象
    UserDao userDao;
    //精灵dao对象
    ElvesDao elvesDao;
    UserBean userBean;
    //本地广播管理
    LocalBroadcastManager localBroadcastManager;
    //本地广播,更新数据
    LocalUpDataReceiver localUpDataReceiver;
    //更新过滤器
    IntentFilter intentUpDataFilter;
    //精灵总数量
    int number;

    public IllustrateFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment IllustrateFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static IllustrateFragment newInstance(String param1, String param2) {
        IllustrateFragment fragment = new IllustrateFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        //注册广播
        localBroadcastManager = LocalBroadcastManager.getInstance(getActivity());//忘了
        intentUpDataFilter = new IntentFilter();
        intentUpDataFilter.addAction("updateIllustrate");

        localUpDataReceiver = new LocalUpDataReceiver();

        localBroadcastManager.registerReceiver(localUpDataReceiver, intentUpDataFilter);

        userDao = new UserDao(getContext());
        elvesDao = new ElvesDao(getContext());

    }

    /**
     * 从弹出窗口返回时，更新
     */
    @Override
    public void onResume() {
        super.onResume();
        refreshMessages();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localUpDataReceiver);
    }

    /**
     * 刷新信息
     */
    public void refreshMessages() {
        refreshData();
        refreshViews();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_illustrate, container, false);
        initData();
        findViews();
        initViews();
        initListener();
        // Inflate the layout for this fragment
        return view;
    }

    /**
     * 实例化控件
     */
    private void findViews() {
        userAndPointTextView = view.findViewById(R.id.userAndPoint);
        pageTv=view.findViewById(R.id.page_tv);
        previousPageIv = view.findViewById(R.id.previousPage);
        nextPageIv = view.findViewById(R.id.nextPage);
    }

    /**
     * 初始化化控件
     */
    private void initViews() {
        String UserMessages = "持有者:" + userBean.getUser_name() + "，点数:" + userBean.getUser_point();
        userAndPointTextView.setText(UserMessages);
        previousPageIv.setVisibility(View.GONE);
        nextPageIv.setVisibility(View.VISIBLE);
        pageTv.setText(page+"/"+allPage+"页"+"（"+number+"只精灵）");
        addRecyclerView();
    }


    /**
     * 添加列表
     */
    public void addRecyclerView() {
        illustrateRecyclerView = view.findViewById(R.id.illustrate);
        //分两列
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        illustrateRecyclerView.setLayoutManager(layoutManager);
        illustrateRecyclerView.addItemDecoration(new PaddingDecoration(70));
        //添加适配器，添加数据
        if (number>0&&number<6) {
            illustrateAdapter = new IllustrateAdapter(getActivity(), elvesBeanList.subList(0,number), userBean.getUser_point());
            illustrateRecyclerView.setAdapter(illustrateAdapter);
        }else if(number>6) {
            illustrateAdapter = new IllustrateAdapter(getActivity(), elvesBeanList.subList(0,6), userBean.getUser_point());
            illustrateRecyclerView.setAdapter(illustrateAdapter);
        }

    }

    /**
     * 初始化数据
     */
    public void initData() {
        userBean = userDao.userQuery();
        elvesBeanList = elvesDao.allElvesQuery();
        number=elvesBeanList.size();
        int check=elvesBeanList.size()%6;
        if (check==0){
            allPage=(elvesBeanList.size()/6);
        }else {
            allPage=(elvesBeanList.size()/6)+1;
        }

    }

    /**
     * 刷新数据
     */
    public void refreshData() {
        userBean = userDao.userQuery();
        elvesBeanList = elvesDao.allElvesQuery();
        if (page*6<=elvesBeanList.size()){
            illustrateAdapter.switchPageRefreshListData(elvesBeanList.subList((page-1)*6,page*6));
        }else {
            illustrateAdapter.switchPageRefreshListData(elvesBeanList.subList((page-1)*6,elvesBeanList.size()));
        }
    }

    /**
     * 刷新控件
     */
    private void refreshViews() {
        String UserMessages = "持有者:" + userBean.getUser_name() + "，点数:" + userBean.getUser_point();
        userAndPointTextView.setText(UserMessages);
        if (page>1&&page<allPage){
            previousPageIv.setVisibility(View.VISIBLE);
            nextPageIv.setVisibility(View.VISIBLE);
        }else if (page==1){
            previousPageIv.setVisibility(View.GONE);
            nextPageIv.setVisibility(View.VISIBLE);
        }else if (page==allPage){
            previousPageIv.setVisibility(View.VISIBLE);
            nextPageIv.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.previousPage){
            page-=1;
            switchPageRefreshList();
        }else if(v.getId()==R.id.nextPage){
            page+=1;
            switchPageRefreshList();
        }
    }

    /**
     * 本地广播接收
     */
    private class LocalUpDataReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            refreshMessages();
        }
    }

    /**
     * 初始化监听
     */
    public void initListener() {
        previousPageIv.setOnClickListener(this);
        nextPageIv.setOnClickListener(this);
    }

    /**
     * 翻页刷新列表信息
     */
    public void switchPageRefreshList() {
        switchPageRefreshView();
    }

    /**
     * 翻页刷新列表页面
     */
    public void switchPageRefreshView() {
        if (page>1&&page<allPage){
            previousPageIv.setVisibility(View.VISIBLE);
            nextPageIv.setVisibility(View.VISIBLE);
        }else if (page==1){
            previousPageIv.setVisibility(View.GONE);
            nextPageIv.setVisibility(View.VISIBLE);
        }else if (page==allPage){
            previousPageIv.setVisibility(View.VISIBLE);
            nextPageIv.setVisibility(View.GONE);
        }
        pageTv.setText(page+"/"+allPage+"页"+"（"+number+"只精灵）");
        if (page*6<=elvesBeanList.size()){
            illustrateAdapter.switchPageRefreshListData(elvesBeanList.subList((page-1)*6,page*6));
        }else {
            illustrateAdapter.switchPageRefreshListData(elvesBeanList.subList((page-1)*6,elvesBeanList.size()));
        }

    }
}